package com.scs.application.core.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.scs.application.consts.SecurityConsts;

import java.util.concurrent.TimeUnit;

/**
 * @Description:
 */
public class JwtUtils {

    /**
     * 设置token到缓存的
     *
     * @param token 完整的access_token
     */
    public static boolean setTokenToCache(String token, long timeout, TimeUnit unit) {
        if (StringUtils.isBlank(token)) {
            return false;
        }

        String jti = getJti(token);
        CacheUtils.put(SecurityConsts.OAUTH_PREFIX, jti, token);
        return true;
    }

    public static boolean isValid(String token) {
        DecodedJWT jwt = JWT.decode(token);
        if (jwt.getExpiresAt().getTime() < System.currentTimeMillis()) {
            // 时间已过期
            return false;
        }
        return true;
    }

    public static String getJti(String token) {
        DecodedJWT jwt = JWT.decode(token);
        Claim claim = jwt.getClaim("jti");
        if (claim == null) {
            return null;
        }
        return claim.asString();
    }

    public static String getTokenByJti(String jti) {
        return CacheUtils.get(SecurityConsts.OAUTH_PREFIX, jti).toString();
    }

    public static boolean removeTokenByJti(String jti) {
        CacheUtils.remove(SecurityConsts.OAUTH_PREFIX, jti);
        return true;
    }
}
